﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;

namespace DrinkcounterUi
{
    public class HeikkiProtocol : IProtocol
    {
        public List<Person> GetPersons()
        {
            List<Person> newdata = new List<Person>();

            HttpWebRequest request = null;
            WebResponse response = null;
            Stream stream = null;
            StreamReader reader = null;
            try
            {
                request = (HttpWebRequest)HttpWebRequest.Create(Properties.Settings.Default.HeikinUpdateUrl);
                response = request.GetResponse();
                stream = response.GetResponseStream();
                reader = new StreamReader(stream);

                string data = reader.ReadToEnd();
                if (data.Length > 2)
                {
                    string[] rows = data.Split('\n');
                    foreach (string row in rows)
                    {
                        if (row.Length < 2) break;
                        string[] cols = row.Split('|');
                        Person p = new Person(int.Parse(cols[0]).ToString());
                        p.Name = cols[1];
                        p.Drinks = int.Parse(cols[2]);
                        p.Alcohol = double.Parse(cols[3], CultureInfo.InvariantCulture);
                        p.Idletime = cols[4];

                        newdata.Add(p);
                    }
                }
            }
            finally
            {
                try { reader.Close(); }
                catch { }
                try { stream.Close(); }
                catch { }
                try { response.Close(); }
                catch { }
            }
            return newdata;
        }

        public void AddDrink(string id)
        {
            string url = Properties.Settings.Default.HeikinAddUrl.Replace("[ID]", id);

            HttpWebRequest request = null;
            WebResponse response = null;
            Stream stream = null;
            StreamReader reader = null;
            try
            {
                request = (HttpWebRequest)HttpWebRequest.Create(url);
                response = request.GetResponse();
                stream = response.GetResponseStream();
                reader = new StreamReader(stream);

                string data = reader.ReadToEnd();
                if (!data.StartsWith("OK")) throw new Exception("lol");
            }
            finally
            {
                try { reader.Close(); }
                catch { }
                try { stream.Close(); }
                catch { }
                try { response.Close(); }
                catch { }
            }
        }
    }
}